<!-- 写文章发布模块 -->
<script lang='ts'>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, reactive, toRefs, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { axiosRequests } from "../../hooks/axiosRequest"
//饿了么 上传
import { ElMessage } from 'element-plus'
import axios from 'axios'
import type { UploadProps } from 'element-plus'
//
import type { IToolbarConfig } from '@wangeditor/editor'
import { DomEditor } from '@wangeditor/editor'
export default {
    components: { Editor, Toolbar },
    setup() {
        //地区选择
        const value = ref('')
        const options = [
            {
                value: '北京市',
                label: '北京市',
            },
            {
                value: '上海市',
                label: '上海市',
            },
            {
                value: '天津市',
                label: '天津市',
            },
            {
                value: '重庆市',
                label: '重庆市',
            },
            {
                value: '河南省',
                label: '河南省',
            },
            {
                value: '河北省',
                label: '河北省',
            },
            {
                value: '山西省',
                label: '山西省',
            },
            {
                value: '内蒙古',
                label: '内蒙古',
            },
            {
                value: '辽宁省',
                label: '辽宁省',
            },
            {
                value: '吉林省',
                label: '吉林省',
            },
            {
                value: '黑龙江省',
                label: '黑龙江省',
            },
            {
                value: '江苏省',
                label: '江苏省',
            },
            {
                value: '浙江省',
                label: '浙江省',
            },
            {
                value: '安徽省',
                label: '安徽省',
            },
            {
                value: '福建省',
                label: '福建省',
            },
            {
                value: '江西省',
                label: '江西省',
            },
            {
                value: '山东省',
                label: '山东省',
            },
            {
                value: '湖北省',
                label: '湖北省',
            },
            {
                value: '湖南省',
                label: '湖南省',
            },
            {
                value: '广东省',
                label: '广东省',
            },
            {
                value: '广东省',
                label: '广东省',
            },
            {
                value: '广西',
                label: '广西',
            },
            {
                value: '海南省',
                label: '海南省',
            },
            {
                value: '四川省',
                label: '四川省',
            },
            {
                value: '贵州省',
                label: '贵州省',
            },
            {
                value: '西藏',
                label: '西藏',
            },
            {
                value: '陕西省',
                label: '陕西省',
            },
            {
                value: '甘肃省',
                label: '甘肃省',
            },
            {
                value: '青海省',
                label: '青海省',
            },
            {
                value: '宁夏',
                label: '宁夏',
            },
            {
                value: '新疆',
                label: '新疆',
            },
            {
                value: '香港',
                label: '香港',
            },
            { value: '澳门', label: '澳门', },
            { value: '台湾省', label: '台湾省', },
        ]

        // 编辑器实例，必须用 shallowRef
        const editorRef = shallowRef()
        // 内容 HTML
        const valueHtml = ref('<p>hello</p>')
        const toolbarConfig: Partial<IToolbarConfig> = {}
        const editorConfig: any = {
            placeholder: '请输入内容...',
            MENU_CONF: {},
        }
        toolbarConfig.excludeKeys = [
            //删除 网络图片和插入视频
            "insertImage",
            "group-video"
            // 排除菜单组，写菜单组 key 的值即可
        ]
        //上传图片配置
        editorConfig.MENU_CONF['uploadImage'] = {
            // 上传图片地址
            server: 'http://127.0.0.1:3100/uploadPicture/uploadPicture',
            fieldName: 'file',
            headers: {
                Authorization: localStorage.getItem('token') || ' ',
            },
            meta: {
                type: 'write',
            },
            metaWithUrl: true,
        }
        // 组件销毁时，也及时销毁编辑器
        onBeforeUnmount(() => {
            const editor = editorRef.value
            if (editor == null) return
            editor.destroy()
        })
        const handleCreated = (editor: any) => {
            editorRef.value = editor // 记录 editor 实例，重要！
            console.log("qqq", editor.getAllMenuKeys())
            const toolbar = DomEditor.getToolbar(editor)

            //  const curToolbarConfig = toolbar.getConfig()
            console.log("ww", toolbar) // 当前菜单排序和分组
        }
        //文章标题区域
        const headObj: any = reactive({
            title: ''//标题
        })
        //监听标题的变化
        watch(() => headObj.title, (nw, ow) => {
            console.log(nw, ow)
            if (nw.length > 30) {
                headObj.title = nw.substring(0, 30)
            }
        })

        //发布文章 将内容存放数据库
        const { userpost } = axiosRequests()
        //发布弹窗 选择一些信息
        const dialogTableVisible = ref(false)
        const radio = ref('2')//单选按钮 有无封面
        const radioType = ref('')//文章类型单选按钮
        /**
       *   1 原创
       *   2 转载
       *   3 翻译
       */
        const radioPublish = ref('1')//发布形式单选按钮 默认全部可见
        /**
      * 1 全部可见
      * 2 本人可见
      * 3 粉丝可见
      * 4 非屏蔽可见
      */
        const introduce = ref('')//摘要内容
        const addRemark = ref(false)//添加标签区域
        //总标签
        const labelArray = ['日常生活', '休闲旅游', '热血沸腾', '舒适安逸', '乡土气息', '随手拍']
        //用户选择的标签
        const showLabel = ref<Array<string>>(['休闲旅游'])
        const dialogShow = () => {
            if (headObj.title === '' || valueHtml.value.length < 30) {
                return ElMessage({
                    showClose: true,
                    message: '请完善你的标题或内容（内容不得低于30个字符）',
                    type: 'error',
                })
            }
            dialogTableVisible.value = true
            //默认让简介等于内容的前255个字符
            introduce.value = editorRef.value.getText().slice(0, 255)
        }
        //摘要超过一定字数不再增加
        watch(introduce, (nw, ow) => {
            if (nw.length > 255) {
                introduce.value = nw.substring(0, 255)
            }
        })
        //封面上传
        const files: any = ref('')
        //上传成功图片路径
        const filesurl = ref<string>('1')
        //获取图片信息验证
        function asd() {
            let file = document.getElementById('file') as any
            let images = document.getElementById('images') as any
            let flag = beforeAvatarUpload(file.files[0])
            console.log("图片符合:", flag);
            if (!flag) {
                //不满足条件至为空
                files.value = ''
                return
            }
            files.value = file.files[0]
            for (const filess of file.files) {
                images.src = URL.createObjectURL(filess);
            }
        }

        function uploadPhoto() {
            let file = document.getElementById('file') as any
            file!.click()
        }
        //发布将内容上传到后端
        async function fabu() {
            //单选图片上传
            if (radio.value === '1') {
                if (files == null || files == undefined) {
                    return alert('暂未获取到图片信息')
                }
                let formdata = new FormData();
                //  formdata.append的属性名 要和后端保持一致 `file`
                formdata.append('file', files.value, files.value.name);
                //上传图片
                let result = await axios.post('http://127.0.0.1:3100/uploadPicture/uploadCover', formdata, {
                    headers: {
                        Authorization: localStorage.getItem('token') || ' ',
                        'Content-Type': 'multipart/form-data',
                    }
                })
                if (result.data.errno === 0) {
                    filesurl.value = result.data.data.url
                    cunfang()
                    ElMessage({
                        showClose: true,
                        message: '上传成功',
                        type: 'success',
                    })
                }
            } else {
                cunfang()
            }

        }
        async function cunfang() {
            if (radioType.value === '') {
                return ElMessage({
                    showClose: true,
                    message: '请选择文章类型',
                    type: 'error',
                })
            }
            if (radioPublish.value === '') {
                return ElMessage({
                    showClose: true,
                    message: '请选择发布形势',
                    type: 'error',
                })
            }
            if (showLabel.value.length == 0 || showLabel.value.length > 3) {
                return ElMessage({
                    showClose: true,
                    message: '请选择文章标签或文章标签过多（最多三个）',
                    type: 'error',
                })
            }
            if (value.value == '') {
                return ElMessage({
                    showClose: true,
                    message: '请选择地区',
                    type: 'error',
                })
            }
            //无封面上传
            let data = {
                filesurl: filesurl.value,//封面图片路径
                title: headObj.title,//标题
                content: valueHtml.value,//文章内容html格式
                introduce: introduce.value,//摘要
                writeType: radioType.value,//文章类型
                publishType: radioPublish.value,//发布形式
                showLabels: JSON.stringify(showLabel.value),//用户所选择的标签
                cityName: value.value,//地区
                isBigArticle: true//是否是长篇文章类型 凡是编辑器所写介属于长文章
            }
            const result = await userpost('/writeArticle/uploadContent', data)
            console.log("wa", result);
            if (result.status === 0) {
                return ElMessage({
                    showClose: true,
                    message: '发布成功',
                    type: 'success',
                })
            }
        }
        const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
            console.log("upload", rawFile.type);

            if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
                ElMessage.error('Avatar picture must be JPG format!')
                return false
            } else if (rawFile.size / 1024 / 1024 > 2) {
                ElMessage.error('Avatar picture size can not exceed 2MB!')
                return false
            }
            return true
        }
        //清空编辑区域
        function clearContent() {
            console.log(123);
            editorRef.value.clear()
        }
        //添加标签内容区域
        function addShowlabel(item: string) {
            showLabel.value.push(item)
            showLabel.value = [...new Set(showLabel.value)]
        }
        return {
            editorRef,
            valueHtml,
            mode: 'default', // 或 'simple'
            toolbarConfig,
            editorConfig,
            handleCreated,
            ...toRefs(headObj),
            dialogTableVisible,
            radio,
            radioType,
            radioPublish,
            introduce,
            addRemark,
            uploadPhoto,
            beforeAvatarUpload,
            asd,
            fabu,
            labelArray,
            showLabel,
            addShowlabel,
            dialogShow,
            value,
            options,
        };
    }
}
</script>
<template>
    <!-- 文本编辑区域 -->
    <div id="EditorBox">
        <div class="operate">
            <span style="margin:0 20px; cursor: pointer;">
                <el-icon style="vertical-align:-2px;">
                    <ArrowLeft />
                </el-icon>文章管理
            </span>
            <div class="titles">
                <input class="inputs" v-model="title" type="text" placeholder=" 【无标题】">
                <span class="countWorld" style="color:black;">{{ title.length }}/30</span>
            </div>
            <div class="operate_right">
                <el-button round size="large" style="width: 110px;font-size:18px;">暂存</el-button>
                <el-button round size="large" style="width: 110px;font-size:18px;" @click="dialogShow">发布
                </el-button>
            </div>
        </div>
        <div>
            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
                :mode="mode" />
            <Editor class="editorArea" style="width:51%;height: 810px;" v-model="valueHtml"
                :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
        </div>
    </div>
    <!--  弹框 -->
    <el-dialog :width="800" v-model="dialogTableVisible" :close-on-click-modal="false" title="发布文章">
        <div
            style="background-color: rgb(255, 236, 230);color:red;display: flex; padding: 10px;font-size: 15px;align-items: center; white-space: nowrap;">
            <el-icon style="font-size: 20px;margin-right: 10px;">
                <Warning />
            </el-icon>
            <span>请勿发布涉及政治、广告、营销、翻墙、不健康内容、违反国家法律法规等内容</span>
        </div>
        <!-- 封面摘要区 -->
        <div class="publishBox">
            <div class="publishleft">
                <span>封面&摘要:</span>
            </div>
            <div class="publishRight">
                <div style="margin-left: 20px;margin-top: 2px;">
                    <el-radio-group v-model="radio">
                        <el-radio label="1" size="large">单图</el-radio>
                        <el-radio label="2" size="large">无封面</el-radio>
                    </el-radio-group>
                </div>
                <div style="display:flex;">

                    <!--    单图上传图片 -->
                    <div class="uploadCover" v-show="radio === '1' ? true : false" @click="uploadPhoto()">
                        <el-icon style="font-size:18px;margin-left:45% ;margin-top: 25%;">
                            <Plus />
                        </el-icon>
                        <input type="file" id="file" accept=".jpg, .jpeg, .png" name="image" @change="asd()">
                        <img src="" alt="" id="images">
                    </div>


                    <div style="flex:1;position: relative;">
                        <textarea class="editor scrollStyle" v-model="introduce" contenteditable="true"
                            placeholder="必填,会在推荐,列表等场景外露，帮助读者快速了解内容！！">
                         </textarea>
                        <span style="position: absolute; right: 10px;bottom: 10px;">
                            {{ introduce.length }}/255
                        </span>
                    </div>
                </div>
            </div>
        </div>
        <!-- 文章标签 -->
        <div class="publishBox">
            <div class="publishleft">
                <span>文章标签:</span>
            </div>
            <div class="publishRight">
                <div>
                    <ul style="display:flex;">
                        <li style="margin-right: 10px;" v-for="item in showLabel">
                            <el-button class="btn" round>{{ item }}</el-button>
                            <el-icon style="color:red;"
                                @click="showLabel.forEach((e: string, index: number) => { if (item === e) { showLabel.splice(index, 1) } })">
                                <Close />
                            </el-icon>
                        </li>
                        <li>
                            <el-button @click="addRemark = true">+添加标签</el-button>
                        </li>
                    </ul>
                </div>
                <template>
                    <el-dialog v-model="addRemark" :width="600" top="460px" title="添加标签" append-to-body>
                        <div class="addLabel">
                            <el-button class="btn" round v-for="item in labelArray" @click="addShowlabel(item)">{{
                                    item
                            }}
                            </el-button>
                        </div>
                    </el-dialog>
                </template>
            </div>
        </div>
        <!-- 地区选择 -->
        <div class="publishBox">
            <div class="publishleft">
                <span>地区选择:</span>
            </div>
            <div class="publishRight">
                <el-select v-model="value" class="m-2" placeholder="Select" size="large">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </div>
        </div>
        <!-- 文章类型 -->
        <div class="publishBox">
            <div class="publishleft">
                <span>文章类型:</span>
            </div>
            <div class="publishRight">
                <el-radio-group v-model="radioType">
                    <el-radio label="1" size="large">原创</el-radio>
                    <el-radio label="2" size="large">转载</el-radio>
                    <el-radio label="3" size="large">翻译</el-radio>
                </el-radio-group>
            </div>
        </div>
        <!-- 发布形势 -->
        <div class="publishBox">
            <div class="publishleft">
                <span>发布形势:</span>
            </div>
            <div class="publishRight">
                <el-radio-group v-model="radioPublish">
                    <el-radio label="1" size="large">全部可见</el-radio>
                    <el-radio label="2" size="large">本人可见</el-radio>
                    <el-radio label="3" size="large">粉丝可见</el-radio>
                    <el-radio label="4" size="large">非屏蔽可见</el-radio>
                </el-radio-group>
            </div>
        </div>
        <div class="publishBox" style="display: flex;justify-content: right;">
            <el-button type="success" round @click="fabu()">确认发布</el-button>
        </div>
    </el-dialog>
</template>
<style lang='scss' scoped>
$spanHeight: 50px; //操作栏的高度

.addLabel {
    width: 100%;

    .btn {
        width: 90px;
        margin-top: 10px;
        margin-right: 10px;
    }
}

#file {
    visibility: hidden;
}

#images {
    position: absolute;
    top: 0;
    width: 160px;
    height: 90px;
}

.uploadCover {
    position: relative;
    width: 160px;
    height: 90px;
    border: 1px dashed gray;
    border-radius: 5px;
    margin-right: 10px;

    &:hover {
        cursor: pointer;
        background-color: rgb(212, 208, 208);
    }
}

.publishBox {
    margin-top: 25px;
    display: flex;

    .publishleft {
        flex: 1;
        width: 100%;
    }

    .publishRight {
        flex: 8;
        margin-top: -12px;
    }
}




.editor {
    width: 100%;
    height: 90px;
    padding: 10px;
    box-sizing: border-box;
    border: 1px solid gray;
    border-radius: 5px;
    outline: none;
    resize: none;
    font-size: 15px;
    color: gray;
}

#EditorBox {
    border: 1px solid #ccc;
    width: 100%;
    height: 100%;

    .operate {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        height: $spanHeight;
        line-height: $spanHeight;
        color: white;
        background-color: rgb(204, 145, 155);

        .titles {
            display: flex;
            align-items: center;
            padding: 0 20px;
            width: 70%;
            height: 35px;
            border-radius: 25px;
            border: 1px solid rgba(255, 255, 255, 0.342);
            background-color: rgb(255, 255, 255);

            .inputs {
                width: 100%;
                height: 30px;
                border: 0;
                outline: none;
                font-size: 18px;
            }

            .countWorld {
                display: inline-block;
                width: 40px;
                height: 35px;
                line-height: 35px;
            }
        }

        .operate_right {
            display: flex;
            align-items: center;
        }
    }

}

.editorArea {
    width: 85%;
    border: 1px solid pink;
    overflow-y: hidden;
    word-wrap: break-word;
    word-break: break-all;
}
</style>
